import React, { PureComponent } from 'react';
import { Modal, Form, Input, Alert, Select, Divider, Spin } from 'antd';
import { Controlled as CodeMirror } from 'react-codemirror2';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/idea.css';
import 'codemirror/mode/javascript/javascript';
// import 'codemirror/addon/selection/active-line';
// import 'codemirror/addon/fold/foldcode';
// import 'codemirror/addon/fold/foldgutter';
// import 'codemirror/addon/edit/matchbrackets';
import ReactJson from 'react-json-view'
import lodash from 'lodash';
import { testEsQuery } from '../../../services/alarm-job-controller';
import { HttpMethodArray } from '../../../utils/enum';
// import classNames from 'classnames';
import styles from './MetricConfigModalEditor.less';

const inItState = {
  // 请求内容
  body: `
{
  "from": "0",
  "size": "1"
}`,
  bodyIsJson: null,
  // 查询ES是否已结束
  esQueryLoading: false,
  // 查询数据结果
  restltData: undefined,
};

@Form.create()
export default class MetricConfigModalEditor extends PureComponent {

  state = {
    ...inItState,
  }

  // 重置组件
  reset = () => {
    this.setState({ ...inItState })
    const { form } = this.props;
    form.resetFields();
  }

  // init
  init = (body) => {
    this.setState({ esQueryLoading: true })
    lodash.delay(() => this.setState({ body, esQueryLoading: false }), 300);
  }

  // 执行ES查询
  esQuery = () => {
    const { body } = this.state;
    try {
      JSON.parse(body);
    } catch (e) {
      this.setState({ bodyIsJson: false });
      return;
    }
    const { form } = this.props;
    form.validateFields((err, formValues) => {
      if (err) return;
      const { method, path } = formValues;
      this.setState({ esQueryLoading: true });
      testEsQuery({ method, path, body }).then(res => this.setState({ esQueryLoading: false, restltData: res }))
        .catch(() => this.setState({ esQueryLoading: false, restltData: { error: '查询ES错误' } }));
    });
  }

  // 保存
  onCreate = () => {
    const { form, onOk, addFlag } = this.props;
    if (!(onOk instanceof Function)) return;
    const { body } = this.state;
    try {
      JSON.parse(body);
    } catch (e) {
      this.setState({ bodyIsJson: false });
      return;
    }
    form.validateFields((err, formValues) => {
      if (err) return;
      const { metricTitle, method, path } = formValues;
      if (addFlag) {
        onOk({ metricTitle, method, path, body, expectValues: [] });
      } else {
        onOk({ metricTitle, method, path, body });
      }
    });
  }

  render() {
    const { body, bodyIsJson, restltData, esQueryLoading } = this.state;
    const { esMetricData, addFlag, metricTitleExists, resetFunc, initFunc, visible, confirmLoading, onCancel, form } = this.props;
    const { getFieldDecorator } = form;
    if (resetFunc instanceof Function) resetFunc(this.reset);
    if (initFunc instanceof Function) initFunc(this.init);
    const width = undefined;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
        md: { span: 2 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
        md: { span: 22 },
      },
    };
    return (
      <Modal
        width="60%"
        style={{ top: 35 }}
        visible={visible}
        confirmLoading={confirmLoading}
        title={`${addFlag ? '新增' : '编辑'}监控项`}
        okText={addFlag ? '新增' : '保存'}
        onCancel={onCancel}
        onOk={this.onCreate}
        maskClosable={false}
        bodyStyle={{ padding: '24px 24px 12px 24px' }}
      >
        <Spin delay={100} spinning={esQueryLoading}>
          <Form layout="horizontal" className={styles.form}>
            <Form.Item label="标题" {...formItemLayout}>
              {getFieldDecorator('metricTitle', {
                initialValue: esMetricData ? esMetricData.metricTitle : undefined,
                validateFirst: true,
                rules: [
                  { required: true, whitespace: true, min: 3, max: 32, message: '监控项标题长度必须是3~32字符' },
                  {
                    validator(_, value, callback) {
                      const errors = [];
                      if (addFlag && value && lodash.trim(value) !== '') {
                        if (metricTitleExists instanceof Function) {
                          if (metricTitleExists(value)) {
                            errors.push("监控项标题不能重复");
                          }
                        }
                      }
                      callback(errors);
                    },
                  },
                ],
              })(
                <Input placeholder="监控项标题" style={{ width }} disabled={!addFlag} />
              )}
            </Form.Item>
            <Form.Item label="请求" {...formItemLayout} style={{ marginBottom: 4 }}>
              {getFieldDecorator('path', {
                initialValue: esMetricData ? esMetricData.path : undefined,
                validateFirst: true,
                rules: [
                  { required: true, whitespace: true, message: '查询Path不能为空' },
                ],
              })(
                <Input
                  placeholder="查询Path，如：/per-summary-*/_search"
                  style={{ width }}
                  addonBefore={
                    getFieldDecorator('method', { initialValue: esMetricData ? esMetricData.method : undefined })(
                      <Select style={{ width: 80 }}>
                        {HttpMethodArray.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
                      </Select>
                    )
                  }
                />
              )}
            </Form.Item>
          </Form>
          <div className={styles.codeMirror}>
            <CodeMirror
              value={body}
              options={{
                mode: 'javascript',
                json: true,
                theme: 'idea',
                lineNumbers: true,
                indentUnit: 2,
                tabSize: 2,
                cursorHeight: 1,
              }}
              onBeforeChange={(_, __, value) => {
                this.setState({ body: value, bodyIsJson: true });
              }}
            />
          </div>
          {(bodyIsJson !== null && bodyIsJson === false) ? (<div style={{ color: '#f5222d' }}>请求Body必须是一个Json格式字符串</div>) : ""}
          <Divider style={{ marginTop: 3, marginBottom: 8, fontSize: 14 }}>
            <a size="small" title="测试查询" onClick={this.esQuery}>查询</a>
          </Divider>
          <div style={{ minHeight: 35, maxHeight: 300, overflowY: 'auto' }}>
            {restltData ?
              (
                <ReactJson
                  src={restltData}
                  name={false}
                  iconStyle="circle"
                  displayObjectSize={true}
                  displayDataTypes={false}
                  enableClipboard={true}
                  collapsed={true}
                />
              ) :
              (
                <Alert message="点击查询预览查询结果" type="info" />
              )}
          </div>
        </Spin>
      </Modal>
    );
  }
}
